﻿/**************************************************************
 *
 * 唯一标识：f5096d64-be17-45ac-bc78-03045aa091d2
 * 命名空间：Sgr.DataCategories.Application.Commands
 * 创建时间：2023/8/17 18:52:25
 * 机器名称：DESKTOP-S0D075D
 * 创建者：antho
 * 电子邮箱：fengqinhua2016@163.com
 * 描述：
 *
 **************************************************************/

using MediatR;
using Sgr.Application.Commands;
using Sgr.DataCategories.Domain.DataCategoryItem;

namespace Sgr.DataCategories.Application.Commands.DataCategoryItem
{
    /// <summary>
    /// 更新数据类别项命令处理器
    /// </summary>
    public class UpdateCategpryItemCommandHandler : IRequestHandler<UpdateCategpryItemCommand, CommandResult<bool>>
    {
        private readonly IDataCategoryItemManage _dataCategoryItemManage;
        private readonly IDataCategoryItemRepository _dataCategoryItemRepository;

        public UpdateCategpryItemCommandHandler(IDataCategoryItemManage dataCategoryItemManage, IDataCategoryItemRepository dataCategoryItemRepository)
        {
            _dataCategoryItemManage = dataCategoryItemManage;
            _dataCategoryItemRepository = dataCategoryItemRepository;
        }

        public async Task<CommandResult<bool>> Handle(UpdateCategpryItemCommand request, CancellationToken cancellationToken)
        {
            //查询数据
            var entity = await _dataCategoryItemRepository.GetAsync(request.Id, cancellationToken);

            if (entity == null)
                return CommandResult.NotFound<bool>("查无数据");

            //更新数据
            entity.UpdateBasicInfo(request.DcItemName, request.Remarks, request.OrderNumber);
            entity.ChangeState(request.State);

            if (request.ParentId.HasValue && request.ParentId.Value > 0 && entity.ParentId != request.ParentId)
            {
                var moveResult = await _dataCategoryItemManage.MoveNodeAsync(entity, request.ParentId.Value, 5, cancellationToken);
                if (!moveResult.IsComply)
                    return CommandResult.Invalid<bool>($"操作失败, {moveResult.Message}");
            }

            await _dataCategoryItemRepository.UpdateAsync(entity, cancellationToken);
            return CommandResult.Success(true);
        }
    }
}